package com.youmingxing.activity.login;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.tencent.upload.task.ITask;
import com.tencent.upload.task.IUploadTaskListener;
import com.tencent.upload.task.data.FileInfo;
import com.youmingxing.R;
import com.youmingxing.activity.BaseActivity;
import com.youmingxing.activity.selfInfo.EditTextActivity;
import com.youmingxing.data.GlobalDataManager;
import com.youmingxing.network.AccountApi;
import com.youmingxing.network.BaseJsonHandler;
import com.youmingxing.network.TXYUploadManager;
import com.youmingxing.utils.Util;

import org.json.JSONObject;

import java.io.File;

import jp.wasabeef.glide.transformations.CropCircleTransformation;
import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.PhotoPickerIntent;

/**
 * @author evilyin(ChenZhixi)
 * @since 2015-9-26
 */

public class CompleteInfoActivity extends BaseActivity implements View.OnClickListener {

    String imageUrl = "";//头像url
    int gender = 0;//性别
    final int EDIT_NAME = 0;
    final int EDIT_IMAGE = 1;
    final int CROP_HEAD_IMG = 2;
    TextView nameTv;
    TextView genderTv;
    TextView numberTv;
    ImageView headImg;
    Button complete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseSetContentView(R.layout.activity_complete_info);
        setTopbarName("完善资料");
        setLeftAndrightTv(false, true, false, R.string.ignore, null, this, null);

        complete = (Button) findViewById(R.id.complete_info);
        complete.setOnClickListener(this);

        View completeName = findViewById(R.id.complete_name);
        completeName.setOnClickListener(this);

        View completeGender = findViewById(R.id.complete_gender);
        completeGender.setOnClickListener(this);

        View completePhone = findViewById(R.id.complete_phone);
        completePhone.setOnClickListener(this);

        headImg = (ImageView) findViewById(R.id.avatar);
        headImg.setOnClickListener(this);
        nameTv = (TextView) findViewById(R.id.name_text);
        genderTv = (TextView) findViewById(R.id.gender_text);
        numberTv = (TextView) findViewById(R.id.number_text);

        //如果是手机登陆的,自动绑定手机
        Bundle bundle = getIntent().getExtras();
        if (bundle != null && bundle.getString("mobile") != null) {
            numberTv.setText(bundle.getString("mobile"));
        }

        //如果是第三方登陆,默认填写第三方登陆的资料
        if (bundle != null && bundle.getBoolean("third_login")) {
            if (bundle.getString("user_image") != null) {
                imageUrl = bundle.getString("user_image");
                Glide.with(this).load(imageUrl)
                        .placeholder(R.drawable.default_avatar).error(R.drawable.default_avatar)
                        .bitmapTransform(new CropCircleTransformation(
                                this)).crossFade().into
                        (headImg);
            }
            nameTv.setText(bundle.getString("user_name"));
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!GlobalDataManager.bindPhone.isEmpty()){
            numberTv.setText(GlobalDataManager.bindPhone);

        }
        setCompleteBtnStyle();
    }

    void setCompleteBtnStyle() {
        if (!nameTv.getText().toString().equals("未设置") && !genderTv.getText().toString().equals
                ("未设置") && !imageUrl.isEmpty()) {
            //四项全部设置好才可以完成,否则只能跳过
            canClick();
        } else {
            notClick();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.header_tv_right:
                //跳过
                finish();
                break;
            case R.id.complete_info:
                completeInfo();
                break;
            case R.id.complete_name:
                Intent intent = new Intent(CompleteInfoActivity.this, EditTextActivity.class);
                intent.putExtra("option", -1);
                intent.putExtra("text", nameTv.getText().toString());
                startActivityForResult(intent, 0);
                break;
            case R.id.complete_gender:
                AlertDialog.Builder builder = new AlertDialog.Builder(CompleteInfoActivity.this);
                final String[] sex = {"男", "女"};
                builder.setItems(sex, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, final int which) {
                        gender = which + 1;
                        genderTv.setText(sex[which]);
                        setCompleteBtnStyle();
                    }
                });
                builder.show();
                break;
            case R.id.avatar:
                PhotoPickerIntent intentPP = new PhotoPickerIntent(CompleteInfoActivity.this);
                intentPP.setPhotoCount(1);
                intentPP.setShowCamera(true);
                intentPP.setShowGif(false);
                startActivityForResult(intentPP, EDIT_IMAGE);
                break;
            case R.id.complete_phone:
                Intent intent1 = new Intent(CompleteInfoActivity.this, RegisterByMobileActivity
                        .class);
                intent1.putExtra("type", 2);
                startActivity(intent1);
                break;
        }

    }

    private void completeInfo() {
        AccountApi.completInfo(nameTv.getText().toString(), imageUrl, gender, new BaseJsonHandler(this) {
            @Override
            public void onSuccessWithData(JSONObject response) {
                GlobalDataManager.bindPhone = "";
                GlobalDataManager.save();
                finish();
            }
        });

    }

    Handler handler = new Handler();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case EDIT_NAME:
                if (resultCode == RESULT_OK) {
                    nameTv.setText(data.getStringExtra("value"));
                    setCompleteBtnStyle();
                }
                break;
            case EDIT_IMAGE:
                if (resultCode == RESULT_OK) {
                    String photoPath = data.getStringArrayListExtra(PhotoPickerActivity
                            .KEY_SELECTED_PHOTOS).get(0);
                    File file = new File(photoPath);
                    Uri mUri = Uri.fromFile(file);
                    if (null == mUri) return;
                    Intent intent = new Intent();
                    intent.setAction("com.android.camera.action.CROP");
                    intent.setDataAndType(mUri, "image/*");// mUri是已经选择的图片Uri
                    intent.putExtra("crop", "true");
                    intent.putExtra("aspectX", 1);// 裁剪框比例
                    intent.putExtra("aspectY", 1);
                    intent.putExtra("outputX", 300);// 输出图片大小
                    intent.putExtra("outputY", 300);
                    intent.putExtra("return-data", true);
                    CompleteInfoActivity.this.startActivityForResult(intent, CROP_HEAD_IMG);
                    break;
                }
            case CROP_HEAD_IMG:
                // 拿到剪切数据
                if (resultCode == RESULT_OK) {
                    Bitmap bmap = data.getParcelableExtra("data");
                    byte[] img = Util.Bitmap2Bytes(Util.compressImage(bmap));
                    bmap.recycle();
                    TXYUploadManager.uploadPhoto(img, new IUploadTaskListener
                            () {
                        @Override
                        public void onUploadSucceed(FileInfo fileInfo) {
                            imageUrl = fileInfo.url;
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    Glide.with(CompleteInfoActivity.this).load(imageUrl)
                                            .placeholder(R.drawable.default_avatar).error(R.drawable.default_avatar)
                                            .bitmapTransform(new CropCircleTransformation(
                                                    CompleteInfoActivity.this)).crossFade().into
                                            (headImg);
                                    setCompleteBtnStyle();
                                }
                            });
                            hideDialog();
                            showToast("上传成功");
                        }

                        @Override
                        public void onUploadFailed(int i, String s) {
                            hideDialog();
                            showToast("上传失败");
                        }

                        @Override
                        public void onUploadProgress(long l, long l1) {

                        }

                        @Override
                        public void onUploadStateChange(ITask.TaskState taskState) {

                        }
                    });
                    showDialog("上传中...");
                }
                break;

        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return keyCode == KeyEvent.KEYCODE_BACK || super.onKeyDown(keyCode, event);
    }

    private void canClick() {
        complete.setClickable(true);
        complete.setBackgroundResource(R.drawable.btn_redbg);
    }

    private void notClick() {
        complete.setClickable(false);
        complete.setBackgroundResource(R.drawable.btn_unable);
    }
}
